package com.yiidata.rpc.grpc;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * <pre>
 *
 * Created by zhenqin.
 * User: zhenqin
 * Date: 2019/4/27
 * Time: 11:58
 * Vendor: yiidata.com
 * To change this template use File | Settings | File Templates.
 *
 * </pre>
 *
 * @author zhenqin
 */
public class HelloServer {
    private Logger logger = LoggerFactory.getLogger(HelloServer.class.getName());

    private static final int DEFAULT_PORT = 8088;

    private int port;//服务端口号

    private Server server;

    public HelloServer(int port) {
        this(port, ServerBuilder.forPort(port));
    }

    public HelloServer(int port, ServerBuilder<?> serverBuilder){
        this.port = port;
        server = serverBuilder
                .addService(new HelloServiceProtocol())
                .addService(new MessageServiceProtocol())
                .build();

    }

    private void start() throws IOException {
        server.start();
        logger.info("Server has started, listening on " + port);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                HelloServer.this.stop();
            }
        });
    }

    private void stop() {
        if(server != null)
            server.shutdown();

    }

    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        HelloServer nameServer;
        if(args.length > 0){
            nameServer = new HelloServer(Integer.parseInt(args[0]));
        }else{
            nameServer = new HelloServer(DEFAULT_PORT);
        }

        nameServer.start();
        nameServer.blockUntilShutdown();
    }
}
